﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace PersonaLibrary.View
{
	/// <summary>
	/// Interaction logic for SelectFromCollection.xaml
	/// </summary>
	public partial class SelectFromCollection
	{
		private DispatcherTimer _timer = new DispatcherTimer();

		public SelectFromCollection()
		{
			InitializeComponent();
			_timer.Tick += _timer_Tick;
			_timer.Interval = TimeSpan.FromMilliseconds(400);
		}

		void _timer_Tick(object sender, EventArgs e)
		{
			_timer.Stop();
			availableValues.Items.Filter = ItemFiltering;
			if (availableValues.Items.Count == 0)
				Ok.IsEnabled = false;
			else if (availableValues.Items.Count == 1)
				availableValues.SelectedItem = availableValues.Items[0];
		}

		public IDictionary Values { set; get; }

		public string SelectedKey { private set; get; }

		public object SelectedValue { private set; get; }

		private void Ok_Click(object sender, RoutedEventArgs e)
		{
			DialogResult = true;
			SelectedKey = value.Text;
			if(availableValues.SelectedItem is KeyValuePair<string, int>)
				SelectedValue = availableValues.SelectedItem = ((KeyValuePair<string, int>) availableValues.SelectedItem).Value;
			Close();
		}

		private void Window_Loaded(object sender, RoutedEventArgs e)
		{
			availableValues.ItemsSource = Values;
		}

		private void availableValues_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (e.AddedItems.Count > 0)
			{
				Ok.IsEnabled = true;
				if (e.AddedItems[0] is KeyValuePair<string, int>)
					value.Text = ((KeyValuePair<string, int>) e.AddedItems[0]).Key;
			}
		}

		private void value_TextChanged(object sender, TextChangedEventArgs e)
		{
			_timer.Stop();
			_timer.Start();
		}

		private bool ItemFiltering(object item)
		{
			if(item is KeyValuePair<string, int>)
			{
				KeyValuePair<string, int> pair = (KeyValuePair<string, int>) item;

				return pair.Key.ToLower().Contains(value.Text.ToLower());
			}
			
			return true;
		}
	}
}
